﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.ComponentModel;
using System.Data.EntityClient;
using System.Reflection;
using System.Data;
using System.Collections.ObjectModel;
using System.Linq.Expressions;

namespace Kocic.RepositoryManagement.EntityFramework4
{
    /// <summary>
    /// Provides additional extensions to Entity Framework classes.
    /// </summary>
    internal static class EntityExtensions
    {
        /// <summary>
        /// Adds an entity object to the object context.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity object to add to the object context.</typeparam>
        /// <param name="context">The object context to which the entity object is to be added to.</param>
        /// <param name="entity">The entity object to add to the object context.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddObject<TEntity>(this ObjectContext context, TEntity entity)
            where TEntity : EntityObject
        {
            if (context == null)
                throw new ArgumentNullException("context", "Object context is null.");

            if (entity == null)
                throw new ArgumentNullException("entity", "Entity object is null");

            context.AddObject(context.GetEntitySetName<TEntity>(entity), entity);
        }

        /// <summary>
        /// Retrieves the entity object's set name from the conceptual model.
        /// </summary>
        /// <typeparam name="TEntity">Type of entity object to retrieve the set name.</typeparam>
        /// <param name="context">The object context used in the retrieving the entity object's set name.</param>
        /// <param name="entity">The entity object to retrieve the set name.</param>
        /// <returns>The entity object's set name.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static String GetEntitySetName<TEntity>(this ObjectContext context, TEntity entity)
            where TEntity : EntityObject
        {
            if (context == null)
                throw new ArgumentNullException("context", "Object context is null.");

            if (entity == null)
                throw new ArgumentNullException("entity", "Entity is null.");

            String setName = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace).BaseEntitySets.Where(item => item.ElementType.Name.Equals(typeof(TEntity).Name)).FirstOrDefault().Name;

            return setName;
        }
    }
}